import {
  BaseEdge,
  type EdgeProps,
  type Edge,
  getBezierPath,
  EdgeLabelRenderer,
  addEdge,
} from "reactflow";
import { MouseEvent } from "react";
import { nanoid } from "nanoid";
import useWorkflowStore from "../../../stores/workflowStore";

const CustomEdge = ({
  sourceX,
  sourceY,
  targetX,
  targetY,
  sourcePosition,
  targetPosition,
  ...props
}: EdgeProps) => {
  const [edgePath, labelX, labelY] = getBezierPath({
    sourceX,
    sourceY,
    sourcePosition,
    targetX,
    targetY,
    targetPosition,
  });

  const { addNode, setEdges, edges } = useWorkflowStore();

  const addNodeFromButton = (event: MouseEvent) => {
    event.preventDefault();
    event.stopPropagation();
    const id = nanoid();

    addNode({
      id: id,
      position: { x: labelX, y: labelY },
      data: { label: id, model: { name: "Deepseek-V3" } },
      type: "llm",
    });

    const edgeId = nanoid();

    const newEdge: Edge = {
      id: edgeId,
      source: id,
      target: props.target,
      type: "customEdge",
      data: {
        hover: false,
      },
    };

    setEdges(
      addEdge(
        newEdge,
        edges.map((item) => {
          if (item.id === props.id) {
            return {
              ...item,
              target: id,
              data: { hover: false },
            };
          }
          return item;
        })
      )
    );
  };

  return (
    <>
      <BaseEdge
        path={edgePath}
        {...props}
        interactionWidth={10}
        style={{
          stroke: `${props.data.hover || props.selected ? "red" : "blue"}`,
          strokeWidth: 3,
        }}
        markerEnd={`url(#${
          props.data.hover || props.selected ? "red" : "blue"
        }-arrow)`}
      />
      <svg>
        <defs>
          <marker
            id="blue-arrow"
            viewBox="0 0 20 20"
            refX="10"
            refY="10"
            markerWidth="6"
            markerHeight="6"
            orient="auto-start-reverse"
          >
            <path d="M 0 0 L 20 10 L 0 20 z" fill="blue" />
          </marker>
          <marker
            id="red-arrow"
            viewBox="0 0 20 20"
            refX="10"
            refY="10"
            markerWidth="6"
            markerHeight="6"
            orient="auto-start-reverse"
          >
            <path d="M 0 0 L 20 10 L 0 20 z" fill="red" />
          </marker>
        </defs>
      </svg>
      {(props.data.hover || props.selected) && (
        <EdgeLabelRenderer>
          <div
            className="w-5 h-5 hover:w-7 hover:h-7 bg-blue-200 rounded-full text-gray-600 text-lg font-bold cursor-pointer flex items-center justify-center transition-transform"
            style={{
              transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
              pointerEvents: "all",
            }}
            onClick={addNodeFromButton}
          >
            +
          </div>
        </EdgeLabelRenderer>
      )}
    </>
  );
};

export default CustomEdge;
